<?php
/**
 * Description: 获取真题
 * User: devforma
 * Date: 15/1/7
 * Time: 16:02
 */

class GetErrorQuestions implements iController {
    private $questionShouldTransform = false;

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $uddb, $cmsdb;
        
        if (empty($queryArgs['ids'])) return genOutput(1000);
            
        $u = validateUser($queryArgs);
        if ($u == 0) return genOutput(1000);

        if ($u == 1) {
            $userIdField = 'user_id';
            $userId = $queryArgs['user_id'];
        } elseif ($u == 2) {
            $userIdField = 'guest_id';
            $userId = $queryArgs['guest_id'];
        } else {
            return genOutput(1000);
        }

        $ids = explode(',', $queryArgs['ids']);
        foreach ($ids as $id) { //校验id的有效性
            if (!is_numeric($id)) return genOutput(1000);
        }
        
        $sql = "SELECT `question_id`, `is_wrong`, `user_answer` FROM `{$uddb->userTests}`
                WHERE `{$userIdField}`=:user AND `question_id` IN ({$queryArgs['ids']})
                ORDER BY FIELD(`question_id`, {$queryArgs['ids']})";
        $answers = $uddb->getResults($sql, array(':user' => $userId));

        if (empty($answers)) return genOutput(1000);

        //新版题目格式改动
        if (!empty($queryArgs['app_version']) && version_cmp($queryArgs['app_version'], '1.1') >= 0)
            $this->questionShouldTransform = true;

        //格式处理
        $exist = array();
        $answerArray = array();
        foreach ($answers as $answer) {
            if (in_array($answer->question_id, $exist)) //滤重
                continue;

            $answerArray[] = array(
                'id' => intval($answer->question_id),
                'is_wrong' => $answer->is_wrong ? true : false,
                'answer' => $answer->user_answer
            );

            $exist[] = $answer->question_id;
        }

        return genOutput(1, array(
            'questions' => $this->questionShouldTransform ? getQuestionsByIds($ids) : getQuestions($ids),
            'answers' => $answerArray
        ));
    }
}